package com.chat;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.*;

/**
 * 在线咨询对话
 * 发送消息
 */
public class TalkSend implements Runnable {
    DatagramSocket socket = null;
    BufferedReader reader = null;

    private int fromPort;
    private String toIP;
    private int toPort;

    public TalkSend(int fromPort, String toIP, int toPort) {
        this.fromPort = fromPort;
        this.toIP = toIP;
        this.toPort = toPort;
        try {
            socket = new DatagramSocket(this.fromPort);
            reader = new BufferedReader(new InputStreamReader(System.in));
        } catch (SocketException e) {
            e.printStackTrace();
        }
    }

    @Override
    public void run() {
        // 发送消息
        while (true) {
            try{
                String data = reader.readLine();
                byte[] dataBytes = data.getBytes();
                // 组装发送数据包
                DatagramPacket packet = new DatagramPacket(dataBytes, 0, dataBytes.length, new InetSocketAddress(this.toIP,this.toPort));
                // 发送数据包
                socket.send(packet);
                if (data.equals("bye")) {
                    break;
                }
            }catch (Exception e) {
                e.printStackTrace();
            }
        }
        // 关闭资源流
        socket.close();
    }
}
